package site.shenjie.spring.rest.template.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import site.shenjie.spring.rest.template.entity.HouseInfo;

/**
 * 沈杰
 * 2020-7-24 09:44:03
 * 控制器：用于测试调用HouseController内的服务
 */
@RestController
public class HouseClientController {
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/index")
    public String index() {
        return "<h1>Hello, Welcome to index page!</h1>";
    }

    @RequestMapping("/call/hello")
    public String callHello() {
        String result = "";
        for (int i = 0; i < 100; i++) {
            result = restTemplate.getForObject("http://eureka-client-user-service/user/hello", String.class);
            System.out.println(result);
        }

        return result;
    }

    @RequestMapping("/call/data")
    public HouseInfo getHouseInfoData(@RequestParam("name") String name) {
        return restTemplate.getForObject("http://spring-rest-template/house/data?name=" + name, HouseInfo.class);
    }

    @RequestMapping("/call/data/{name}")
    public String getData2(@PathVariable("name") String name) {
        return restTemplate.getForObject("http://localhost:8885/house/data/{name}", String.class, name);
    }

    @RequestMapping("/call/dataEntity")
    public HouseInfo getHouseInfoEntity(@RequestParam("name") String name) {
        ResponseEntity<HouseInfo> responseEntity;
        responseEntity = restTemplate.getForEntity("http://localhost:8885/house/data?name=" + name, HouseInfo.class);
        if (responseEntity.getStatusCodeValue() == 200) {
            return responseEntity.getBody();
        }
        return null;
    }

    @GetMapping("/call/save")
    public Long add() {
        HouseInfo houseInfo = new HouseInfo();
        houseInfo.setAddress("中国·云南");
        houseInfo.setName("×××");
        Long id = restTemplate.postForObject("http://localhost:8885/house/save", houseInfo, Long.class);
        return id;
    }
}
